package per.srp.demo.carLink.Utils;

import java.io.*;
import java.net.Socket;

public class SocketOperation {

    private static void write(Socket socket,String msg,boolean close) throws IOException {
        if(socket!=null&&!socket.isClosed()){
            OutputStream os = socket.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            bos.write(msg.getBytes());
            bos.flush();
            if(close) socket.shutdownOutput();
        }
    }
    public static void write(Socket socket,String msg) throws IOException {
        write(socket,msg,false);
    }

    public static void writeAndClose(Socket socket,String msg) throws IOException {
        write(socket,msg,true);
    }

    public static String read(Socket socket) throws IOException {
        if(socket!=null&&!socket.isClosed()){
            InputStream is = socket.getInputStream();
            InputStreamReader isw = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isw);
            return br.readLine();
        }
        return null;
    }
}
